import useLinkStore from '@/stores/link'
import type { Link } from '@/types/connect'
import { RedisTypeColor } from '@/enums/redisEnum'

const linkStore = useLinkStore()

/**
 * 从链接参数生产 redis url
 * @param {Link} linkInfo 链接参数
 */
export function getRedisUrl(linkInfo: Link) {
  const check = checkLinkParam(linkInfo)
  if (check == false) {
    return false
  }
  if (null == linkInfo.password || '' == linkInfo.password) {
    return 'redis://' + linkInfo.host + ':' + linkInfo.port
  }
  const un = linkInfo.userName === '' ? 'default' : linkInfo.userName
  return 'redis://' + un + ':' + linkInfo.password + '@' + linkInfo.host + ':' + linkInfo.port
}
/**
 * 参数合法性检测
 * @param {Link} linkInfo 参数
 * @returns boolean
 */
export function checkLinkParam(linkInfo: Link) {
  // 判断参数合格性
  // ip地址
  const ipv4Regex =
    /^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})){3}$/
  // 端口号
  const portRegex = /^(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3})$/

  if (!ipv4Regex.test(linkInfo.host) || !portRegex.test(linkInfo.port.toString())) {
    return false
  }
  return true
}
/**
 * 判断是否已经存在
 * @param link 
 */
export function hasLink(link: Link) {
  let has = false;
  const links = linkStore.links;
  links.filter((lk) => {
    if (lk.linkName === link.linkName) {
      has = true;
    }
  })
  return has;
}
/**
 * 通过类型获取颜色
 * @param keyType 
 */
export function getBgColor(keyType: string) {
  let bgColor;
  switch (keyType) {
    case 'string':
      bgColor = RedisTypeColor.STRING;
      break;
    case 'hash':
      bgColor = RedisTypeColor.HASH;
      break;
    case 'list':
      bgColor = RedisTypeColor.LIST;
      break;
    case 'set':
      bgColor = RedisTypeColor.SET;
      break;
  }
  return bgColor as string;
}